package cn.tedu.knows.portal.controller;

import cn.tedu.knows.portal.exception.ServiceException;
import cn.tedu.knows.portal.service.IUserService;
import cn.tedu.knows.portal.vo.RegisterVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@RestController
@Slf4j
public class SystemController {

    @Autowired
    private IUserService userService;

    @PostMapping("/register")
    public String register(RegisterVO registerVO){
        log.debug("接收到表单信息:{}",registerVO);
        try{
            userService.registerStudent(registerVO);
            return "ok";
        }catch (ServiceException e){
            log.error("业务异常!",e);
            return e.getMessage();
        }

    }


    @Value("${knows.upload.path}")
    private File uploadPath;
    @Value("${knows.upload.host}")
    private String uploadHost;

    @PostMapping("/upload/file")
    public String upload(MultipartFile imageFile) throws IOException {

        String path= DateTimeFormatter.ofPattern("yyyy/MM/dd")
                                .format(LocalDateTime.now());
        File folder=new File(uploadPath,path);// E:/upload/2022/02/10

        folder.mkdirs();
        String filename=imageFile.getOriginalFilename();
        String ext=filename.substring(filename.lastIndexOf("."));
        String name= UUID.randomUUID().toString()+ext;
        File file=new File(folder,name);
        imageFile.transferTo(file);

        String url=uploadHost+"/"+path+"/"+name;
        return url;

    }




}
